package drds.plus.sql_process.optimizer.cost_esitimater.statistics.parse;

import com.google.common.collect.Lists;
import drds.plus.common.utils.XmlHelper;
import drds.plus.sql_process.optimizer.cost_esitimater.statistics.TableStatistics;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * 解析matrix配置
 */
public class TableStatisticsParser {

    private static final String XSD_SCHEMA = "META-INF/stat.xsd";

    public static List<TableStatistics> parse(String data) {
        InputStream is = new ByteArrayInputStream(data.getBytes());
        return parse(is);
    }

    public static List<TableStatistics> parse(InputStream in) {
        Document doc = XmlHelper.createDocument(in, null);
        Element root = doc.getDocumentElement();

        List<TableStatistics> stats = Lists.newArrayList();
        NodeList list = root.getElementsByTagName("tableStat");
        for (int i = 0; i < list.getLength(); i++) {
            Node item = list.item(i);
            stats.add(parseTableStat(item));
        }
        return stats;
    }

    private static TableStatistics parseTableStat(Node node) {
        NodeList list = node.getChildNodes();
        TableStatistics stat = new TableStatistics();
        for (int i = 0; i < list.getLength(); i++) {
            Node item = list.item(i);
            if ("tableName".equals(item.getNodeName())) {
                stat.setTableName(item.getFirstChild().getNodeValue().toLowerCase());
            } else if ("tableRows".equals(item.getNodeName())) {
                stat.setRowCount(Long.valueOf(item.getFirstChild().getNodeValue()));
            }

        }

        return stat;
    }
}
